const { MongoClient, ServerApiVersion } = require('mongodb')
const uri = 'mongodb://LunaLovegood:Luna1040@ac-tzndspj-shard-00-00.un8n2rn.mongodb.net:27017,ac-tzndspj-shard-00-01.un8n2rn.mongodb.net:27017,ac-tzndspj-shard-00-02.un8n2rn.mongodb.net:27017/?ssl=true&replicaSet=atlas-ik07hi-shard-0&authSource=admin&retryWrites=true&w=majority'
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 })
client.connect((err) => {
  const collection = client.db('test').collection('devices')
  // perform actions on the collection object
  client.close()
})

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(
  bodyParser.urlencoded({
    extended: false
  })
)
app.use(bodyParser.json())
app.all('*', function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header('Access-Control-Allow-Origin', '*')
  //允许的header类型
  res.header('Access-Control-Allow-Headers', 'content-type')
  //跨域允许的请求方式
  res.header('Access-Control-Allow-Methods', 'DELETE,PUT,POST,GET,OPTIONS')
  if (req.method.toLowerCase() == 'options') res.send(200) //让options尝试请求快速结束
  else next()
})

// 注册
app.post('/api/user/register', function (req, res) {
  let data = req.body
  if (data.SMSCode !== '111111') {
    res.send({
      status: 500,
      success: false,
      code: 2
      //未知错误
    })
    return
  }
  if (data.inviteCode !== '111111') {
    res.send({
      status: 500,
      success: false,
      code: 4
      //未知错误
    })
    return
  }
  client.connect((err) => {
    if (err) {
      res.send({
        status: 500,
        success: false,
        code: 0
        //未知错误
      })
      return
    }
    const user = client.db('user')
    user
      .collection('userList')
      .find({ username: data.username })
      .toArray((err, resData) => {
        if (err) {
          res.send({
            status: 500,
            success: false,
            code: 0
          })
          return
        }
        for (let i = 0; i < resData.length; i++) {
          if (resData[i].username === data.username) {
            res.send({
              status: 500,
              success: false,
              code: 1
              // 用户名已存在
            })
            return
          }
        }
        user.collection('userList').insertOne(data, function (err, resData) {
          if (err) {
            res.send({
              status: 500,
              success: false,
              code: 0
              //未知错误
            })
            return
          }
          return res.send({
            status: 200,
            success: true,
            data: req.body
          })
        })
      })
  })
})
//验证邀请码
app.post('/api/user/checkInviteCode', function (req, res) {
  let data = req.body
  client.connect((err) => {
    if (err) {
      res.send({
        status: 500,
        success: false,
        code: 99
        //未知错误
      })
      return
    }
    const user = client.db('user')
    user
      .collection('userList')
      .find({ inviteCode: data.inviteCode })
      .toArray((err, resData) => {
        if (err) {
          res.send({
            status: 500,
            success: false,
            code: 99
          })
          return
        }
        if (data.inviteCode === '111111') {
          res.send({
            status: 200,
            success: true,
            code: 0
          })
          return
        } else {
          res.send({
            status: 500,
            success: false,
            code: 1
          })
        }
      })
  })
})
app.post('/api/user/login', function (req, res) {
  let data = req.body
  client.connect((err) => {
    if (err) {
      res.send({
        status: 500,
        success: false,
        code: 99
        //未知错误
      })
      return
    }
    const user = client.db('user')
    user
      .collection('userList')
      .find({ username: data.username })
      .toArray((err, resData) => {
        if (err) {
          res.send({
            status: 500,
            success: false,
            code: 99
          })
          return
        }
        if (resData.length === 1) {
          if (resData[0].username === data.username && data.SMSCode === '111111') {
            res.send({
              status: 200,
              success: true,
              code: 1
            })
            return
          } else {
            res.send({
              status: 555500,
              success: false,
              code: 2
            })
            return
          }
        } else {
          res.send({
            status: 500,
            success: false,
            code: 2
          })
          return
        }
      })
  })
})

app.listen('3000', function () {
  console.log('服务已启动')
})
